package com.weakteam.mobile.minimum.service.task;

import com.weakteam.mobile.minimum.common.util.SimpleLog;
import com.weakteam.mobile.minimum.common.util.UrlBuilder;
import com.weakteam.mobile.minimum.service.AsyncRequest;
import com.weakteam.mobile.minimum.service.ServerData;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Nail on 29.11.2014.
 */
public class Authenticate extends AsyncRequest {

    private String phoneNumber;
    private String password;
    private boolean success;
    private String errorMessage;

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isSuccess() {
        return success;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    @Override
    protected Void doInBackground(Void... params) {
        final String baseURL = ServerData.getInstance().getBaseServerUrl();
        final URL url = new UrlBuilder().setServerURL(baseURL)
                .addParameter("t", "15")
                .addParameter("l", this.phoneNumber)
                .addParameter("p", this.password)
                .getURL();

        try {
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.setConnectTimeout(CONNECTION_TIME_OUT);
            connection.setReadTimeout(CONNECTION_TIME_OUT);

            // get response
            int status = connection.getResponseCode();

            switch (status) {
                case HttpURLConnection.HTTP_OK:
                    final String response = this.readStream(connection);

                    final char code = response.charAt(0);
                    this.success = code == '1';
                    if (response.length() > 2) {
                        this.errorMessage = response.substring(2);
                    }

                    break;
                default:
                    SimpleLog.info("status code: " + status);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}